#!/bin/bash

function pow
{
	BASE=$1
	EXPONENT=$2
	RESULT=1

	for ((I=0;I<EXPONENT;I++))
	do
		RESULT=$(($RESULT * $BASE))
	done

	echo $RESULT
}

function ip_to_number
{
	W=`echo $1 | cut -d'.' -f1`
	X=`echo $1 | cut -d'.' -f2`
	Y=`echo $1 | cut -d'.' -f3`
	Z=`echo $1 | cut -d'.' -f4`

	echo $((16777216 * $W + 65536 * $X + 256 * $Y + $Z))
}

function number_to_ip
{
	W=$((($1/16777216)%256))
	X=$((($1/65536)%256))
	Y=$((($1/256)%256))
	Z=$(($1%256))
	
	echo $W.$X.$Y.$Z
}

function range_to_ips
{
	START_IP=`echo $@ | cut -d'-' -f1 | sed -r -e 's/^ *//' -e 's/ *$//'`
	STOP_IP=`echo $@ | cut -d'-' -f2 | sed -r -e 's/^ *//' -e 's/ *$//'`

	START_NUMBER=`ip_to_number $START_IP`
	STOP_NUMBER=`ip_to_number $STOP_IP`

	for ((I=START_NUMBER;I<=STOP_NUMBER;I++))
	do
		number_to_ip $I
	done
}

function cidr_to_ips
{
	NETWORK_ADDRESS=`echo $@ | cut -d'/' -f1`
	NETMASK=`echo $@ | cut -d'/' -f2`

	START_NUMBER=`ip_to_number $NETWORK_ADDRESS`
	STOP_NUMBER=$((`pow 2 $((32 - $NETMASK))` + $START_NUMBER - 1))

	for ((I=START_NUMBER;I<=STOP_NUMBER;I++))
	do
		number_to_ip $I
	done
}

while read IP_OR_RANGE
do
	case `echo $IP_OR_RANGE | grep -o -e '-' -e '/'` in
		'-') range_to_ips $IP_OR_RANGE;;
		'/') cidr_to_ips $IP_OR_RANGE;;
		  *) echo $IP_OR_RANGE;;
	esac
done
